package com.wyl.filter

import javax.servlet.*
import javax.servlet.annotation.WebFilter
import javax.servlet.http.HttpServletResponse


@WebFilter("/servlet/*")
class CharacterEncodingFilter : Filter {
    override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
        request.characterEncoding = "utf-8"
        response.contentType = "text/html;charset=UTF-8"

        println("CharacterEncodingFilter执行前...")

        val username = request.getParameter("username")
        if (username.isNullOrEmpty()) {
            chain.doFilter(request, response)
        } else {
            (response as HttpServletResponse).apply {
                sendRedirect("/cookie01")
            }
        }

        println("CharacterEncodingFilter执行后...")
    }

    override fun destroy() {
        println("CharacterEncodingFilter销毁: web服务器关闭的时候。过滤器销毁")
    }

    override fun init(filterConfig: FilterConfig?) {
        println("CharacterEncodingFilter初始化: web服务器启动，就已经初始化了，随时等待过滤对象出现!")
    }
}
